package com.wxp.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.models.constant.JafCoreConstant;
import com.models.constant.MessageConstant;
import com.modules.annotation.MenuMapping;
import com.modules.annotation.ResourceMapping;
import com.modules.annotation.ResourceMapping.Operation;
import com.modules.persistence.DynamicSpecifications;
import com.modules.web.CRUDController;
import com.wxp.entity.Resource;
import com.wxp.entity.Role;
import com.wxp.entity.User;
import com.wxp.service.ResourceService;
import com.wxp.service.RoleService;

@Controller
@RequestMapping("/role/roleInfo")
@MenuMapping(name = "角色信息", operator = "role10", parentOperator = "larry")
public class RoleController extends CRUDController{
    private static Logger logger	= LoggerFactory.getLogger(RoleController.class);

   
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private ResourceService resourceService;

    @RequestMapping("/list")
    @RequiresPermissions ("role:list")
    @ResourceMapping(name = "角色列表", operation = Operation.MENU)
    public String list(Model model){
        return "role/roleList";
    }
    
   
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @RequiresPermissions ("role:list")
    @ResponseBody
    public Map<String, Object> query(HttpServletRequest request) throws Exception {

        Page page = onPrepareQueryData(request);
        return  transferTo(page);
    }
    
    protected Page onPrepareQueryData(HttpServletRequest request) throws Exception {
    	Specification spec = DynamicSpecifications.bySearchFilter(request);//查询条件(基本查询条件)
        PageRequest pageRequest = DynamicSpecifications.buildPageRequest(request,null);//相关的分页
        Page<Role> page = roleService.findAll(spec,pageRequest);
        return page;//用来查询相关的数据
    }

    @RequiresPermissions ("role:add")//权限
    @ResourceMapping(name = "添加角色", operation = Operation.BUTTON)
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String showAddPage(Model model) {
        return "role/roleEdit";
    }
    
    @RequiresPermissions ("role:view")//权限
    @ResourceMapping(name = "角色信息查看", operation = Operation.BUTTON)
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String showViewPage(Model model) {
        
        return "role/roleEdit";
    }

    /**
     * 返回编辑页面
     * @param id
     * @return 编辑页面
     */
    @RequiresPermissions ("role:edit")
    @ResourceMapping(name = "角色信息编辑页面", operation = Operation.BUTTON)
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String showEditPage(String id,  Model model) {

        return "role/roleEdit";
    }


    /**
     * 获取指定primary key的实体对象（数据库记录）
     */
    @RequiresPermissions ("role:edit")
    @RequestMapping(value = "/edit/{id}")
    @ResponseBody
    public User getEditData(@PathVariable String id) {
        User user = null;
        try {
            //user = userService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
           // logger.error(e.getMessage(), e);
        }
        return user;
    }
    /**
     * 保存是作为新建和编辑按钮的辅助性操作，可以认为保存是新建和保存下的子操作
     * 辅助操作的权限不用进行显示
     * */
    @RequiresPermissions (value={"role:edit", "role:add"},logical=Logical.OR)
    @RequestMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(Role role) {
        Map<String, Object> tips = new HashMap<String, Object>();
        String result = roleService.save(role);
		if (JafCoreConstant.OUT_OF_DATE.equals(result)){
			tips.put(MessageConstant.SUCCESS, false);
			tips.put(MessageConstant.MSG, MessageConstant.FAILURE_OUT_OF_DATE);
		}else{
			tips.put(MessageConstant.SUCCESS, true);
			tips.put(MessageConstant.MSG, MessageConstant.SUCCESS_SAVE);
		
		}
        return tips;
    }
    
    
    @RequiresPermissions ("role:delete")//权限跟其先关的操作是一样的
    @RequestMapping(value = "/delete/{id}")
    @ResourceMapping(name = "角色信息删除", operation = Operation.BUTTON)
    @ResponseBody
    public Map<String,String> delete(@PathVariable String id){
    	Map<String,String> map = new HashMap<String, String>();
    	return map;
    }
    
    
   
    @RequiresPermissions ("role:addPermission")
    @ResourceMapping(name = "角色添加权限", operation = Operation.BUTTON)
    @RequestMapping(value = "/addPermission")
    public String addPermission() {
    	
        return "role/resourcetree";
    }
    
    @RequiresPermissions ("role:addPermission")
    @RequestMapping(value = "/findPermission", method = RequestMethod.POST)
    @ResponseBody
    public List<Resource> findPermission(String roleCode){
    	List<Resource> list = resourceService.findAll(roleCode);
    	return list;
    }
    
    
    @RequiresPermissions ("role:addPermission")
    @RequestMapping(value = "/savePermission", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> savePermission(String roleCode,String data){
	    Map<String, Object> tips = new HashMap<String, Object>();
	   	try {
	   		roleService.savePermission(roleCode, data);
			tips.put(MessageConstant.SUCCESS, true);
			tips.put(MessageConstant.MSG, MessageConstant.SUCCESS_SAVE);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			tips.put(MessageConstant.SUCCESS, false);
			tips.put(MessageConstant.MSG, MessageConstant.FAILURE_SAVE);
		}
	   	return tips;
    }
    
    
    
    
}
